<?php

namespace app\modules\user\controllers;

use app\models\User;
use app\models\UserLog;
use app\models\UserProfileForm;
use Yii;
use yii\web\Response;

/**
 * 用户信息管理
 * Class IdentityController
 * @package app\modules\user\controllers
 */
class IdentityController extends BaseController
{
    /**
     * 用户退出
     * @return Response
     */
    public function actionLogout()
    {
        UserLog::info($this->user->id, 'LOGOUT', '退出');
        $this->user->logout();
        $this->user->setReturnUrl(['/user']);
        return $this->redirect(['/user/login']);
    }

    /**
     * 用户设置
     * @return string
     */
    public function actionProfile()
    {
        $model = new UserProfileForm();
        $user = User::findOne(['id' => $this->user->id]);
        $model->setAttributes($user->attributes, false);
        if ($model->load($this->post()) && $model->validate() && $model->save()) {
            UserLog::info($this->user->id, 'SAVE_USER', '保存账号信息', print_r($model->attributes, true));
            // 更新Session
            $user->refresh();
            Yii::$app->user->setIdentity($user);
            Yii::$app->session->addFlash('success', '用户信息已保存。');
        }
        return $this->render('profile', [
            'model' => $model
        ]);
    }
}
